import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../serve/docx_reader_service.dart';
import '../serve/file_serve.dart';

/// 增强的DOCX查看器组件，支持分页显示和位置记忆
class EnhancedDocxViewer extends StatefulWidget {
  final String filePath;
  final String? docId;
  final FileServe? fileServe;
  final String? title;
  final int wordsPerPage; // 每页显示的字数

  const EnhancedDocxViewer({
    Key? key,
    required this.filePath,
    this.docId,
    this.fileServe,
    this.title,
    this.wordsPerPage = 800, // 默认每页800字
  }) : super(key: key);

  @override
  _EnhancedDocxViewerState createState() => _EnhancedDocxViewerState();
}

class _EnhancedDocxViewerState extends State<EnhancedDocxViewer> {
  final DocxReaderService _docxReader = DocxReaderService();
  final TextEditingController _pageController = TextEditingController();
  final TextEditingController _searchController = TextEditingController();
  final ScrollController _scrollController = ScrollController();

  DocxContent? _docxContent;
  List<String> _pages = [];
  List<SearchResult> _searchResults = [];
  
  int _currentPage = 0;
  int _totalPages = 0;
  bool _isLoading = true;
  String? _errorMessage;
  bool _isSearching = false;
  int _currentSearchIndex = -1;

  @override
  void initState() {
    super.initState();
    _loadDocxContent();
  }

  @override
  void dispose() {
    _pageController.dispose();
    _searchController.dispose();
    _scrollController.dispose();
    _saveCurrentPosition();
    super.dispose();
  }

  /// 加载DOCX内容并分页
  Future<void> _loadDocxContent() async {
    try {
      setState(() {
        _isLoading = true;
        _errorMessage = null;
      });

      final content = await _docxReader.readDocxFile(widget.filePath);
      
      setState(() {
        _docxContent = content;
      });

      // 分页处理
      _splitContentIntoPages();
      
      // 加载上次阅读位置
      await _loadLastReadingPosition();
      
      setState(() {
        _isLoading = false;
      });

    } catch (e) {
      setState(() {
        _errorMessage = e.toString();
        _isLoading = false;
      });
    }
  }

  /// 将内容分割成页面
  void _splitContentIntoPages() {
    if (_docxContent == null) return;

    final content = _docxContent!.content;
    final words = content.split(RegExp(r'\s+'));
    
    _pages.clear();
    
    for (int i = 0; i < words.length; i += widget.wordsPerPage) {
      final endIndex = (i + widget.wordsPerPage).clamp(0, words.length);
      final pageWords = words.sublist(i, endIndex);
      _pages.add(pageWords.join(' '));
    }
    
    _totalPages = _pages.length;
    print('DOCX查看器: 内容分页完成，总页数: $_totalPages');
  }

  /// 加载上次阅读位置
  Future<void> _loadLastReadingPosition() async {
    if (widget.docId != null && widget.fileServe != null) {
      try {
        final position = await widget.fileServe!.getDocumentReadingPosition(widget.docId!);
        if (position != null) {
          final lastPage = position['current_page'] ?? 0;
          setState(() {
            _currentPage = lastPage.clamp(0, _totalPages - 1);
          });
          print('DOCX查看器: 加载上次阅读位置 - 第 $lastPage 页');
        }
      } catch (e) {
        print('DOCX查看器: 加载阅读位置失败: $e');
      }
    }
  }

  /// 保存当前阅读位置
  Future<void> _saveCurrentPosition() async {
    if (widget.docId != null && widget.fileServe != null && _totalPages > 0) {
      try {
        await widget.fileServe!.saveDocumentReadingPosition(
          widget.docId!,
          _currentPage,
          _totalPages,
        );
      } catch (e) {
        print('DOCX查看器: 保存阅读位置失败: $e');
      }
    }
  }

  /// 跳转到指定页面
  void _goToPage(int page) {
    if (page >= 0 && page < _totalPages) {
      setState(() {
        _currentPage = page;
      });
      // 立即保存新的页面位置
      _saveCurrentPosition();
      _scrollController.animateTo(
        0,
        duration: Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
      print('DOCX查看器: 成功跳转到第 ${page + 1} 页并保存位置');
    }
  }

  /// 上一页
  void _previousPage() {
    if (_currentPage > 0) {
      _goToPage(_currentPage - 1);
    }
  }

  /// 下一页
  void _nextPage() {
    if (_currentPage < _totalPages - 1) {
      _goToPage(_currentPage + 1);
    }
  }

  /// 显示页面跳转对话框
  void _showPageJumpDialog() {
    _pageController.text = (_currentPage + 1).toString();
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('跳转到页面'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('总共 $_totalPages 页，当前第 ${_currentPage + 1} 页'),
            SizedBox(height: 16),
            TextField(
              controller: _pageController,
              keyboardType: TextInputType.number,
              decoration: InputDecoration(
                labelText: '页码',
                hintText: '输入页码 (1-$_totalPages)',
                border: OutlineInputBorder(),
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              final page = int.tryParse(_pageController.text);
              if (page != null && page >= 1 && page <= _totalPages) {
                Navigator.of(context).pop();
                _goToPage(page - 1); // 转换为0基础索引
              } else {
                _showErrorSnackBar('请输入有效的页码 (1-$_totalPages)');
              }
            },
            child: Text('跳转'),
          ),
        ],
      ),
    );
  }

  /// 执行搜索
  Future<void> _performSearch(String keyword) async {
    if (keyword.isEmpty) {
      setState(() {
        _searchResults = [];
        _currentSearchIndex = -1;
      });
      return;
    }

    setState(() {
      _isSearching = true;
    });

    try {
      final results = await _docxReader.searchInDocx(widget.filePath, keyword);
      setState(() {
        _searchResults = results;
        _currentSearchIndex = results.isNotEmpty ? 0 : -1;
        _isSearching = false;
      });

      if (results.isNotEmpty) {
        _highlightSearchResult(0);
      }
    } catch (e) {
      setState(() {
        _isSearching = false;
      });
      _showErrorSnackBar('搜索失败: $e');
    }
  }

  /// 高亮搜索结果
  void _highlightSearchResult(int index) {
    if (index >= 0 && index < _searchResults.length) {
      setState(() {
        _currentSearchIndex = index;
      });
      
      // 计算搜索结果在哪一页
      final searchResult = _searchResults[index];
      // 由于SearchResult使用lineNumber，我们需要重新计算在哪一页
      final lines = _docxContent!.content.split('\n');
      int charCount = 0;
      for (int i = 0; i < (searchResult.lineNumber - 1) && i < lines.length; i++) {
        charCount += lines[i].length + 1; // +1 for newline
      }
      final contentBefore = _docxContent!.content.substring(0, charCount);
      final wordsBefore = contentBefore.split(RegExp(r'\s+'));
      final pageIndex = (wordsBefore.length / widget.wordsPerPage).floor();
      
      if (pageIndex != _currentPage) {
        _goToPage(pageIndex);
      }
    }
  }

  /// 显示错误提示
  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red[400],
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return _buildLoadingView();
    }

    if (_errorMessage != null) {
      return _buildErrorView();
    }

    return Column(
      children: [
        // 搜索栏
        _buildSearchBar(),
        
        SizedBox(height: 16),
        
        // 文档内容
        Expanded(
          child: Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(20),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  blurRadius: 20,
                  offset: Offset(0, 10),
                ),
              ],
            ),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(20),
              child: _buildDocumentContent(),
            ),
          ),
        ),
        
        SizedBox(height: 16),
        
        // 页面导航控制栏
        _buildNavigationBar(),
      ],
    );
  }

  Widget _buildLoadingView() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 20,
            offset: Offset(0, 10),
          ),
        ],
      ),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation<Color>(
                Color(0xFF667eea),
              ),
            ),
            SizedBox(height: 16),
            Text(
              '正在加载Word文档...',
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey[600],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildErrorView() {
    return Container(
      padding: EdgeInsets.all(32),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 20,
            offset: Offset(0, 10),
          ),
        ],
      ),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              padding: EdgeInsets.all(24),
              decoration: BoxDecoration(
                color: Colors.red[50],
                borderRadius: BorderRadius.circular(20),
                border: Border.all(color: Colors.red[200]!),
              ),
              child: Icon(
                Icons.error_outline,
                size: 48,
                color: Colors.red[400],
              ),
            ),
            SizedBox(height: 16),
            Text(
              'Word文档加载失败',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w600,
                color: Colors.grey[700],
              ),
            ),
            SizedBox(height: 8),
            Text(
              _errorMessage ?? '未知错误',
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey[500],
              ),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSearchBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20, vertical: 12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.08),
            blurRadius: 16,
            offset: Offset(0, 8),
          ),
        ],
      ),
      child: Row(
        children: [
          Expanded(
            child: TextField(
              controller: _searchController,
              decoration: InputDecoration(
                hintText: '搜索文档内容...',
                border: InputBorder.none,
                prefixIcon: Icon(Icons.search, color: Colors.grey[400]),
                suffixIcon: _searchController.text.isNotEmpty
                    ? IconButton(
                        icon: Icon(Icons.clear, color: Colors.grey[400]),
                        onPressed: () {
                          _searchController.clear();
                          _performSearch('');
                        },
                      )
                    : null,
              ),
              onChanged: _performSearch,
            ),
          ),
          
          if (_searchResults.isNotEmpty) ...[
            SizedBox(width: 12),
            Text(
              '${_currentSearchIndex + 1}/${_searchResults.length}',
              style: TextStyle(
                fontSize: 12,
                color: Colors.grey[600],
              ),
            ),
            SizedBox(width: 8),
            IconButton(
              icon: Icon(Icons.keyboard_arrow_up, size: 20),
              onPressed: _currentSearchIndex > 0
                  ? () => _highlightSearchResult(_currentSearchIndex - 1)
                  : null,
            ),
            IconButton(
              icon: Icon(Icons.keyboard_arrow_down, size: 20),
              onPressed: _currentSearchIndex < _searchResults.length - 1
                  ? () => _highlightSearchResult(_currentSearchIndex + 1)
                  : null,
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildDocumentContent() {
    if (_pages.isEmpty) {
      return Center(
        child: Text(
          '文档内容为空',
          style: TextStyle(
            fontSize: 16,
            color: Colors.grey[500],
          ),
        ),
      );
    }

    final currentPageContent = _pages[_currentPage];
    final searchKeyword = _searchController.text;

    return SingleChildScrollView(
      controller: _scrollController,
      padding: EdgeInsets.all(24),
      child: searchKeyword.isNotEmpty && _searchResults.isNotEmpty
          ? _buildHighlightedContent(currentPageContent, searchKeyword)
          : SelectableText(
              currentPageContent,
              style: TextStyle(
                fontSize: 16,
                height: 1.6,
                color: Colors.black87,
              ),
            ),
    );
  }

  Widget _buildHighlightedContent(String content, String keyword) {
    return RichText(
      text: _buildHighlightedText(content, keyword),
    );
  }

  TextSpan _buildHighlightedText(String content, String keyword) {
    final List<TextSpan> spans = [];
    final RegExp regex = RegExp(keyword, caseSensitive: false);
    int lastMatchEnd = 0;

    for (final match in regex.allMatches(content)) {
      // 添加匹配前的普通文本
      if (match.start > lastMatchEnd) {
        spans.add(TextSpan(
          text: content.substring(lastMatchEnd, match.start),
          style: TextStyle(fontSize: 16, height: 1.6, color: Colors.black87),
        ));
      }

      // 添加高亮的匹配文本
      spans.add(TextSpan(
        text: match.group(0),
        style: TextStyle(
          fontSize: 16,
          height: 1.6,
          backgroundColor: Colors.yellow[300],
          color: Colors.black87,
          fontWeight: FontWeight.bold,
        ),
      ));

      lastMatchEnd = match.end;
    }

    // 添加最后的普通文本
    if (lastMatchEnd < content.length) {
      spans.add(TextSpan(
        text: content.substring(lastMatchEnd),
        style: TextStyle(fontSize: 16, height: 1.6, color: Colors.black87),
      ));
    }

    return TextSpan(children: spans);
  }

  Widget _buildNavigationBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20, vertical: 12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.08),
            blurRadius: 16,
            offset: Offset(0, 8),
          ),
        ],
      ),
      child: Row(
        children: [
          // 上一页按钮
          _buildNavButton(
            icon: Icons.chevron_left,
            tooltip: '上一页',
            onPressed: _currentPage > 0 ? _previousPage : null,
          ),
          
          SizedBox(width: 12),
          
          // 页面信息
          Expanded(
            child: GestureDetector(
              onTap: _totalPages > 0 ? _showPageJumpDialog : null,
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                decoration: BoxDecoration(
                  color: Colors.grey[100],
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      '第 ${_currentPage + 1} 页',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                        color: Colors.grey[700],
                      ),
                    ),
                    if (_totalPages > 0) ...[
                      Text(
                        ' / $_totalPages',
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.grey[500],
                        ),
                      ),
                      SizedBox(width: 8),
                      Icon(
                        Icons.touch_app,
                        size: 16,
                        color: Colors.grey[500],
                      ),
                    ],
                  ],
                ),
              ),
            ),
          ),
          
          SizedBox(width: 12),
          
          // 下一页按钮
          _buildNavButton(
            icon: Icons.chevron_right,
            tooltip: '下一页',
            onPressed: _currentPage < _totalPages - 1 ? _nextPage : null,
          ),
        ],
      ),
    );
  }

  Widget _buildNavButton({
    required IconData icon,
    required String tooltip,
    VoidCallback? onPressed,
  }) {
    final isEnabled = onPressed != null;
    
    return Tooltip(
      message: tooltip,
      child: Container(
        width: 44,
        height: 44,
        decoration: BoxDecoration(
          gradient: isEnabled
              ? LinearGradient(
                  colors: [Color(0xFF667eea), Color(0xFF764ba2)],
                )
              : null,
          color: isEnabled ? null : Colors.grey[200],
          borderRadius: BorderRadius.circular(12),
          boxShadow: isEnabled
              ? [
                  BoxShadow(
                    color: Color(0xFF667eea).withOpacity(0.3),
                    blurRadius: 8,
                    offset: Offset(0, 4),
                  ),
                ]
              : null,
        ),
        child: Material(
          color: Colors.transparent,
          borderRadius: BorderRadius.circular(12),
          child: InkWell(
            borderRadius: BorderRadius.circular(12),
            onTap: onPressed,
            child: Center(
              child: Icon(
                icon,
                color: isEnabled ? Colors.white : Colors.grey[400],
                size: 20,
              ),
            ),
          ),
        ),
      ),
    );
  }
} 